%{*********************************************************************
Replication code for Systemic Discrimination Among Large U.S. Employers
Patrick M. Kline, Evan K. Rose, Christopher R. Walters
April, 2022

This file produces the two-way fixed effect estimates of firm contact
penalty variances. It requires the modified version of code from Kline,
Saggio, and Solvsten 2020 contained in the subfolder /kss.
%*********************************************************************%}

% Set up KSS code
clear
cd 'code/kss'
path(path,'codes'); %this contains the main LeaveOut Routines. path(path,'CMG'); % CMG package http://www.cs.cmu.edu/~jkoutis/cmg.html 
[result,output] = evalc('installCMG(1)'); %installs CMG routine (silently) 
delete(gcp("nocreate")) %clear parallel envir.
c = parcluster('local'); %tell me # of available cores
nw = c.NumWorkers; %tell me # of available cores 
pool=parpool(nw,'IdleTimeout', Inf); %all cores will be assigned to Matlab

% Characteristics
chars = {'black','female','over40'}
groups = {'st','soc3'}

% Collect results
results = {}

% Loop over characteristics and groups
for c = 1:length(chars)
	for g = 1:length(groups)
		%% Import data.
		namesrc=append('data/',chars{c},'_',groups{g},'_firm.csv'); 
		data=importdata(namesrc);
		id=data(:,1);
		firmid=data(:,2); 
		y=data(:,3);
		clear data

		%% Run. Works only for variance of firm effects.
		[sigma2_psi,sigma_psi_alpha,sigma2_alpha,Nobs,Nmovers,Nfirms] = leave_out_KSS(y,id,firmid,[],'obs','exact');
		r = {chars{c}, groups{g}, sigma2_psi^0.5, sigma2_alpha^0.5, sigma_psi_alpha, Nobs, Nfirms, size(unique(id),1), Nmovers, -mean(y)};
		results = [results; r]
	end
end

% Save
T = cell2table(results,'VariableNames',{'attribute','second_fe','sd_firm','sd_second','covar','njobs','nfirms','nsecond','nmovers','meangap'});
cd ..
cd ..
writetable(T,'dump/table7a.csv')
